<script setup lang="ts">
import type { Ref } from "vue";
import type { IConversation } from "@src/types";

import useStore from "@src/store/store";
import { ref, inject, onMounted, onUnmounted } from "vue";
// import { getConversationIndex } from "@src/utils";

import {
  CheckIcon,
  FaceSmileIcon,
  MicrophoneIcon,
  PaperAirplaneIcon,
  PaperClipIcon,
  XCircleIcon,
} from "@heroicons/vue/24/outline";

import IconButton from "@src/components/ui/inputs/IconButton.vue";

import Textarea from "@src/components/ui/inputs/Textarea.vue";
import { post } from "@src/network/axios"
import useCustomerStore from "@src/store/customerStore";
import useServiceStore from "@src/store/serviceStore";
import { uploadFile } from "@src/network/api";

const store = useStore();
const customerStore = useCustomerStore();

const activeConversation = <IConversation>inject("conversations");

// var ws:WebSocket; // 发送websocket
var serviceId = '' // kf-demo1
var uid = '' // user-demo1

// the content of the message.
const value: Ref<string> = ref("");

// determines whether the app is recording or not.
const recording = ref(false);

// open emoji picker.
const showPicker = ref(false);

// open modal used to send multiple attachments attachments.
const openAttachmentsModal = ref(false);

// start and stop recording.
const handleToggleRecording = () => {
  recording.value = !recording.value;
};

const serviceStore = useServiceStore()

const message = ref('');

const handleSendMsg = () => {
  if (serviceStore.currentConversationRelationId) {
    var relation = serviceStore.conversationRelations[serviceStore.currentConversationRelationId];
    if(relation == undefined) {
      //查是不是在history中
      relation = serviceStore.conversationRelationsHistory[serviceStore.currentConversationRelationId];
    }
  if (message.value.trim() !== '') {
    const msg = {
      "type":"text",
        "content":message.value,
        'round':'s2c',
        'website_id':relation.service.website_id,
        'service_id':relation.service.id,
        'customer_id':relation.customer_id
    }
    const str = JSON.stringify(msg);
    serviceStore.ws?.send(str);
    message.value = '';
  }
}
};

const handleSendFile = (fileurl:string) => {
  if (serviceStore.currentConversationRelationId) {
    var relation = serviceStore.conversationRelations[serviceStore.currentConversationRelationId];
    if(relation == undefined) {
      //查是不是在history中
      relation = serviceStore.conversationRelationsHistory[serviceStore.currentConversationRelationId];
    }
  if (fileurl.trim() !== '') {
    const msg = {
      "type":"file",
        "content":fileurl,
        'round':'s2c',
        'website_id':relation.service.website_id,
        'service_id':relation.service.id,
        'customer_id':relation.customer_id
    }
    const str = JSON.stringify(msg);
    serviceStore.ws?.send(str);
  }
}
};

function getCurrentTime() {
    const date = new Date(); // 创建日期对象
    let hours = date.getHours(); // 小时（0-23）
    let minutes = date.getMinutes(); // 分钟（0-59）
    let seconds = date.getSeconds(); // 秒钟（0-59）
    
    if (minutes < 10) {
      // result = result + ':0' + minutes; // 补全两位数格式
      return `${hours}:0${minutes}`
    } else {

      return `${hours}:${minutes}`
    }
  }

function updateMsgs() {
  if (value.value == 'openAi' && serviceId != '') {
    openAi()
  }

};


// 开启ai机器人
function openAi(){
  if (serviceId == '') {
    serviceId = 'kf-demo1'
  }
  if (uid == '') {
    uid = 'user-demo1'
  }

  post('http://api.aivodesk.com/aichat/v1/chat/openAI', {'serviceId':serviceId, 'customerId':uid})
  .then(function (response:any) {
    })
    .catch(function (error:any) {
    });
}

// 关闭机器人
function closeAi(){
  if (serviceId == '') {
    serviceId = 'kf-demo1'
  }
  if (uid == '') {
    uid = 'user-demo1'
  }

  post('http://api.aivodesk.com/aichat/v1/chat/closeAI', {'serviceId':serviceId, 'customerId':uid})
    .then(function (response:any) {
    })
    .catch(function (error:any) {
    });
}


// stop recording without sending.
const handleCancelRecording = () => {
  recording.value = false;
};

// close picker when you click outside.
const handleClickOutside = (event: Event) => {
  let target = event.target as HTMLElement;
  let parent = target.parentElement as HTMLElement;

  if (
    target &&
    !target.classList.contains("toggle-picker-button") &&
    parent &&
    !parent.classList.contains("toggle-picker-button")
  ) {
    showPicker.value = false;
  }
};

// (event) set the draft message equals the content of the text area
const handleSetDraft = () => {
  // const index = getConversationIndex(activeConversation.id);
  // if (index !== undefined) {
  //   store.conversations[index].draftMessage = value.value;
  // }
};

const fileChange = ((event:any) => {
  const file = event.target.files[0];
  // file.name
  // file.type
  const formData = new FormData();
  console.log(file)
  formData.append('file', file);
  console.log(formData)
  uploadFile(formData).then((res)=>{
    console.log(res)
    if (res.code == '10000') {
      const fileUrl = res.data.file.url
      handleSendFile(fileUrl)
    }
  })
  
})

onUnmounted(() => {
  closeAi()
})

onMounted(() => {
  
  if (activeConversation.id == 1) {
    uid = ''
    serviceId = 'kf-demo1'
    // setupServerWebSocket()
  } else {
    // uid = activeConversation.id
    uid = 'user-demo1'
    serviceId = ''
    // setupClientWebSocket()
  }
});
</script>

<template>
  <div class="w-full">
    <!--回复指定消息-->
    <!-- <div
      class="relative transition-all duration-200"
      :class="{ 'pt-[60px]': activeConversation }"
    >
      <ReplyMessage />
    </div> -->

    <div
      class="h-auto min-h-[84px] p-5 flex items-end"
      v-if="store.status !== 'loading'"
      :class="recording ? ['justify-between'] : []"
    >
      <div class="min-h-[44px]">
        <div class="min-h-[44px]">
        <div class="icons flex text-gray-500 m-2">
                <label id="select-image">
                    <svg class="mr-2 cursor-pointer hover:text-gray-700 border rounded-full p-1 h-7" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                    </svg>
                   <input hidden type="file" multiple @change="fileChange" x-ref="fileInput">

                </label>
            </div>
        </div>
        <!--select attachments button-->
        <!-- <IconButton
          title="open select attachments modal"
          aria-label="open select attachments modal"
          @click="openAttachmentsModal = true"
          v-if="!recording"
          class="group w-7 h-7 md:mr-5 xs:mr-4"
        >
          <PaperClipIcon
            class="w-[20px] h-[20px] text-gray-400 group-hover:text-indigo-300"
          />
        </IconButton> -->

        <!--recording timer-->
        <!-- <Typography
          v-if="recording"
          variant="body-1"
          no-color
          class="text-indigo-300"
          >00:11</Typography
        > -->
      </div>

      <!--message textarea-->
      <div class="grow md:mr-5 xs:mr-4 self-end" v-if="!recording">
        <div class="relative">
          <Textarea
            v-model="message"
            :value="message"
            @sendMsg="handleSendMsg"
            class="max-h-[80px] pr-[50px] resize-none scrollbar-hidden"
            auto-resize
            cols="30"
            rows="1"
            placeholder="Write your message here"
            aria-label="Write your message here"
          />

          <!--emojis-->
          <!-- <div class="absolute bottom-[13px] right-0">
            <IconButton
              title="toggle emoji picker"
              aria-label="toggle emoji picker"
              @click="showPicker = !showPicker"
              class="toggle-picker-button group w-7 h-7 md:mr-5 xs:mr-4"
            >
              <XCircleIcon
                v-if="showPicker"
                class="w-[20px] h-[20px] text-gray-400 group-hover:text-indigo-300"
              />
              <FaceSmileIcon
                v-else
                class="w-[20px] h-[20px] text-gray-400 group-hover:text-indigo-300"
              />
            </IconButton>
            <ScaleTransition>
              <div
                v-click-outside="handleClickOutside"
                v-show="showPicker"
                class="absolute z-10 bottom-[55px] md:right-0 xs:right-[-80px] mt-2"
              >
                <div role="none">
                  <EmojiPicker :show="showPicker" />
                </div>
              </div>
            </ScaleTransition>
          </div> -->
        </div>
      </div>

      <!--cancel recording button-->
      <!-- <div class="min-h-[44px]">
        <div v-if="recording" @click="handleCancelRecording">
          <Button variant="ghost" color="danger"> Cancel </Button>
        </div>
      </div> -->

      <div class="min-h-[44px] flex">
        <!--finish recording button-->
        <!-- <IconButton
          title="finish recording"
          aria-label="finish recording"
          v-if="recording"
          @click="handleToggleRecording"
          class="relative group w-7 h-7 flex justify-center items-center outline-none rounded-full bg-indigo-300 hover:bg-green-300 dark:hover:bg-green-400 dark:focus:bg-green-400 focus:outline-none transition-all duration-200"
        >
          <span
            class="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-300 group-hover:bg-green-300 opacity-40"
          >
          </span>

          <MicrophoneIcon
            class="w-[20px] h-[20px] text-white group-hover:hidden"
          />
          <CheckIcon
            class="w-[20px] h-[20px] hidden text-white group-hover:block"
          />
        </IconButton> -->

        <!--start recording button-->
        <!-- <IconButton
          v-else
          @click="handleToggleRecording"
          title="start recording"
          aria-label="start recording"
          class="group w-7 h-7 md:mr-5 xs:mr-4"
        >
          <MicrophoneIcon
            class="w-[20px] h-[20px] text-gray-400 group-hover:text-indigo-300"
          />
        </IconButton> -->

        <!--send message button-->
        <IconButton
          v-if="!recording"
          @click="handleSendMsg"
          class="group w-7 h-7 bg-indigo-300 hover:bg-indigo-400 focus:bg-indigo-400 dark:focus:bg-indigo-300 dark:bg-indigo-400 dark:hover:bg-indigo-400 active:scale-110"
          variant="ghost"
          title="send message"
          aria-label="send message"
        >
          <PaperAirplaneIcon class="w-[17px] h-[17px] text-white" />
        </IconButton>
      </div>
    </div>
    
    <!-- 附件弹窗
    <AttachmentsModal
      :open="openAttachmentsModal"
      :close-modal="() => (openAttachmentsModal = false)"
    /> -->
  </div>
</template>

<style>
input[placeholder="Search emoji"] {
  background: rgba(0, 0, 0, 0);
}

.v3-emoji-picker .v3-header {
  border-bottom: 0;
}

.v3-emoji-picker .v3-footer {
  border-top: 0;
}
</style>
